// 注册表单验证
const register_form = document.forms['register-form'];

// 代表正确和错误的样式
const error_icon_class = "glyphicon glyphicon-remove color-red";
const right_icon_class = "glyphicon glyphicon-ok";

// 账号、用户名、密码、重复密码、邮箱
const account = register_form.account;
const username = register_form.username
const password = register_form.password
const repassword = register_form.re_password
const email = register_form.email

// 提交按钮
const submit = document.querySelector("#register_from_submit")

// 输入提示对象
const hint = {};
hint.show = function (hint,message){
    hint.style.display = "block"
    hint.innerHTML = message
}
hint.hidden = function(hint) {
    hint.style.display = "none";
}
hint.getHint = function(input) {
    return document.querySelector('#' + input.getAttribute('hint-target'));
}
hint.initHint = function (input,message){
    var h = this.getHint(input);

    input.addEventListener("focus",function (){
        hint.show(h,message)
    })

    input.addEventListener("blur", function () {
        hint.hidden(h)
    })
}
// 输入提示对象结束

// 账户
// 由大小写字母、数字组成
// 至少6位，至多12位

account.addEventListener("input", function () {verify(account, /^\w{6,12}$/)})
hint.initHint(account,"账号可以由大小写字母、数字组成，至少6位，最多12位")

// 用户名
// 用户名由任意字符组成
// 至少2位，最多16位
username.addEventListener("input", function () {verify(username, /^.{2,16}$/)})
hint.initHint(username,"用户名由任意字符组成，至少2位，最多16位")

// 密码
// 最短6位，最长16位 {6,16}
// 可以包含小写大母 [a-z] 和大写字母 [A-Z]
// 可以包含数字 [0-9]
// 可以包含下划线 [ _ ] 和减号 [ - ]
password.addEventListener("input", function () {
    verify(password, /^[\w_-]{6,16}$/)
    checkpwd()
})
hint.initHint(password,"账号可以由大小写字母、数字以及 '_' 和 '-' 组成，至少6位，最多12位")

// 重复密码
repassword.addEventListener("input", function (){checkpwd()})
hint.initHint(repassword,"重复刚才输入的密码")

// 邮箱
email.addEventListener("input", function () {verify(email, /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/)})

// 提交按钮
submit.addEventListener("click", function (e) {
    if(username.check && account.check && password.check && repassword.check && email.check){
        console.log("all right!")
    } else {
        document.querySelector("#myModal").showRegisterAlter("检查输入是否正确")
        e.preventDefault()
    }
})

function verify(elem, regexp) {
    const label = elem.nextElementSibling.childNodes[0]

    if (regexp.test(elem.value)) {
        label.className = right_icon_class
        label.style.color = "limegreen"
        elem.check = true;
    } else {
        label.className = error_icon_class
        label.style.color = "red"
        elem.check = false;
    }
}

function checkpwd() {
    const label = repassword.nextElementSibling.childNodes[0]

    if (repassword.value === password.value && password.value.length !== 0) {
        label.className = right_icon_class
        label.style.color = "limegreen"
        repassword.check = true;
    } else {
        label.className = error_icon_class
        label.style.color = "red"
        repassword.check = false;
    }
}